package com.jay.io.clazz;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

public class ObjectStreamFieldCls {

	public static void main(String[] args) throws ClassNotFoundException,
			IOException {
		System.out.println("-------------------");
		Msg msg = (Msg) serialize();
		System.out.println(msg.getHead());
		System.out.println(msg.getTag());
		System.out.println(msg.getText());
		System.out.println(msg.getB());

	}

	public static Object serialize() throws IOException, ClassNotFoundException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		Msg msg = new Msg("H", 1, null, 'f');
		oos.writeObject(msg);
		ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(bais);
		return ois.readObject();
	}
}

class Msg implements Serializable {
	private String head = "";
	private int tag = 0;
	private String text;
	private transient char b;

	public Msg(String head, int tag, String text, char b) {
		this.head = head;
		this.tag = tag;
		this.text = text;
		this.b = b;
	}

	public char getB() {
		return b;
	}

	public void setB(char b) {
		this.b = b;
	}

	public String getHead() {
		return head;
	}

	public void setHead(String head) {
		this.head = head;
	}

	public int getTag() {
		return tag;
	}

	public void setTag(int tag) {
		this.tag = tag;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	private void writeObject(ObjectOutputStream out) throws IOException {
		System.out.println("writeObject invoked");

		ObjectOutputStream.PutField pf = out.putFields();
		pf.put("head", "HD");
		pf.put("tag", 88);
		pf.put("text", "Hello Mami.");
		//error
//		pf.put("b", 'a');
		out.writeFields();
	}

	private void readObject(ObjectInputStream in) throws IOException,
			ClassNotFoundException {
		System.out.println("readObject invoked");
		ObjectInputStream.GetField gf = in.readFields();
		this.head = (String) gf.get("head", "");
		this.tag = gf.get("tag", 111);
		this.text = (String) gf.get("text", "");
//		this.b = gf.get("b", 'b');
	}

	private Object writeReplace() throws ObjectStreamException {
		System.out.println("writeReplace invoked");
		return this;
	}

	private Object readResolve() throws ObjectStreamException {
		System.out.println("readResolve invoked");
		return this;
	}

}